<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

/**
 * 前台公共库文件
 * 主要定义前台公共函数库
 */

/**
 * 获取当前班级名称
 * @param  integer $bj_code 班级代码
 * @return $bj_name     班级名称
 * @author 水月居 <singliang@163.com>
 */
function get_bjname($bj_code = 0)
    {
        static $class_list;

        /* 获取缓存数据 */
        if (empty($class_list)) {
            $class_list = S('sys_class_list');
        }

        /* 查找班级名称 */
        $key = "b{$bj_code}";
        if (isset($class_list[$key])) { //已缓存，直接使用
            $bj_name = $class_list[$key];
        } else { //调用接口获取用户信息
            $info = M('JfClass')->field('bj_name')->where(array('bj_code'=>$bj_code))->find();
            if ($info !== false && $info['bj_name']) {
                $bj_name = $info['bj_name'];
                $class_list[$key] = $bj_name;
                /* 缓存班级 */
                $count = count($class_list);
                $max = 100;// C('USER_MAX_CACHE')
                while ($count-- > $max) {
                    array_shift($class_list);//删除除第一个键值的数组
                }
                S('sys_class_list', $class_list);
            } else {
                $bj_name = '';
            }
        }
        return $bj_name;
    }
/**
 * 获取当前班级代码
 * @param  integer $bj_name 班级名称
 * @return $bj_code     班级代码
 * @author 水月居 <singliang@163.com>
 */
function get_bjcode($bj_name = '')
    {

            $info = M('JfClass')->field('bj_code')->where(array('bj_name'=>$bj_name))->find();
           // dump($info);die;
            if ($info !== false && $info['bj_code']) {
                $bj_code = $info['bj_code'];

            } else {
                $bj_code = '';
            }
 
        return $bj_code;
    }


    /**
     * @param  [type] $xlsdata  [导出数据]
     * @param  [type] $savefile [导出的文件名]
     * @param  string $pageset  [页面是否为横向]
     * @return [type]           [导出excel文件]
     */
function exportOneExcelByTitle($xlsdata,$savefile=null,$properties=null )
    {
        if(!is_array($xlsdata)){return false;}
        //若没有指定文件名则为当前时间戳
        if(is_null($savefile)){
            $savefile=time();
        }
        //导入phpExcel类
        vendor("PHPExcel");

        $objPHPExcel = new PHPExcel();
        // dump($properties)
         
         /*文件属性设置 **/        
            $file_creator=$properties['creator']?$properties['creator']:'水月居';
            $file_category=$properties['category']?$properties['category']:'excel表格';
            $objPHPExcel->getProperties()  
                             ->setCreator($file_creator) //设置创建者  
                             ->setLastModifiedBy(date('Y-m-d',time())) //设置时间  
                             ->setTitle('Office 2013 天台县外国语学校') //设置标题  
                             ->setSubject($file_category) //设置备注  
                             ->setDescription('ttwgy天台县外国语学校小学部') //设置描述  
                             ->setKeywords($file_creator) //设置关键字 | 标记  
                             ->setCategory($file_category); //设置类别 
       

        $sheetIndex = 0;

        foreach ($xlsdata as $k => $Adata) {

            $sheetname = $Adata['sheetname'];
            $header = $Adata['header'];
            $title = $Adata['title'];
            $w = $Adata['width'];
            $data = $Adata['data'];
            $pageset = $Adata['$pageset'];

            //判断data为空时不执行，防止死机
            if(!$data){
                echo '<span style="color:red">没有你想要导出的数据</span>';
                exit;
            }

            $allcol = count($data[0])-1; //取总列数
            //计算列数字符
            $allcolABC = PHPExcel_Cell::stringFromColumnIndex($allcol);

            //多表
            if($sheetIndex>0){
                $objPHPExcel->createSheet();
            }
            $obj=$objPHPExcel->setActiveSheetIndex($sheetIndex);
            //是否设置页面为横向
            if($pageset){
               $obj->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE); 
            }

            /*样式默认设置项目*/
            $obj->getPageSetup()->setPaperSize(PHPExcel_Worksheet_PageSetup:: PAPERSIZE_A4); //设置纸张大小为A4
            $obj->getDefaultStyle()->getFont()->setName('宋体');
            $obj->getDefaultStyle()->getFont()->setSize('10');
            $obj->getDefaultRowDimension()->setRowHeight($w['defaultRowHeight']);//设置默认行高
            $obj->getDefaultColumnDimension()->setWidth($w['defaultWidth']);//设置默认列宽
            $obj->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER)
                                          ->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);//设置水平、垂直居中
            //写入头部标题
            $start_row =count($header)+1; 

            if(is_array($header)){
                
                foreach($header as $m=>$v){
                  $m++;
                  $obj->mergeCells('A'.$m.':'.$allcolABC.$m);
                  $obj->setCellValue('A'.$m,$v); //写入头部总标题 
                                  $obj->getStyle('A'.$m)->applyFromArray(array(
                    'font' => array('size' => 12,'bold' => false,'name' => '宋体' ),                 
                    'alignment' => array( 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER)
                )); 
                }

                //头部标题加粗居中
                $obj->getStyle('A1')->applyFromArray(array(
                    'font' => array('size' => 18,'bold' => true ),                 
                    'alignment' => array( 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER)
                ));     
            }
            //设置数据列宽
            $width=$w['datawidth'];
            if(is_array($width)){
                for ($i=0;$i<count($width);$i++){ 
                //计算列字符
                $col = PHPExcel_Cell::stringFromColumnIndex($i);    
                    if(is_null($width)){
                        $obj->getColumnDimension($col)->setAutoSize(true);
                    }else{
                        if($width[$i]=='auto'){
                            $obj->getColumnDimension($col)->setAutoSize(true);
                        }else{
                            $obj->getColumnDimension($col)->setWidth($width[$i]);
                        }                     
                    }
                }           
            }
            //若指字了excel表头则添加表头
            //
            //表头样式设置数组
            $title_style=array(
                        'borders' => array('allborders' => array('style' => PHPExcel_Style_Border::BORDER_THIN)),
                        'font' => array(
                                'bold' => true,
                                'color' => array('rgb' => '000000'),
                                'size' => 10,
                                'name' => '宋体'
                        ),
                       'fill' => array (
                              'type'=>PHPExcel_Style_Fill::FILL_SOLID,                             
                              'startcolor' => array (
                                   'argb' => 'FFD9E1F9'
                               ),

                        )
                    );            
            if(is_array($title)){
                $row=$start_row;
                $tNum=1;
                $nn=0;
                foreach($title as $v){
                  $col = PHPExcel_Cell::stringFromColumnIndex($nn); 
                  $obj->setCellValue($col.$row,$v);
                  //自动转换显示字体大小,使内容能够显示
                  $obj->getStyle($col.$row)->getAlignment()->setShrinkToFit(true);
                  $obj->getStyle($col.$row)->applyFromArray($title_style);//表头样式设置
                  $nn++; 
                }
               
            }else{
                $tNum=0;
            }
            //数据表格格式设置+加外边框
            $data_style=array(
                'borders' => array('allborders' => array('style' => PHPExcel_Style_Border::BORDER_THIN)),
                'font' => array(
                        'bold' => false,
                        'color' => array('rgb' => '000000'),
                        'size' => 10,
                        'name' => '宋体'
                       )
            );
                    

            foreach($data as $k => $v){              
                $row=$k+$start_row+$tNum;//数据开始行
                $nn=0;
                foreach($v as $vv){
                    $col = PHPExcel_Cell::stringFromColumnIndex($nn);
                    //防止出现科学计数
                    if(is_numeric($vv) && strlen($vv)>11){
                        $obj->setCellValueExplicit($col.$row,$vv,PHPExcel_Cell_DataType::TYPE_STRING);
                        $obj->getStyle($col.$row)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);
                    }else{
                        $obj->setCellValue($col.$row,$vv);
                    }
                    $obj->getStyle($col.$row)->applyFromArray($data_style);
                    $nn++;
                }

            }
            $obj->setTitle($sheetname);
            $sheetIndex++; //下一张表
        }
        $objPHPExcel->setActiveSheetIndex(0);
        $filename=$savefile.'.xlsx';
        $agent = $_SERVER["HTTP_USER_AGENT"]; 
        
        // dump($agent) ;die;
        $encoded_filename = urlencode($filename);        
        header('Content-Type: application/vnd.ms-excel');
        header('Cache-Control: max-age=0');
        if (preg_match('/FireFox\/([^\s]+)/i', $agent)) {
            // $filename='firefox'.$filename;
            header('Content-Disposition: attachment; filename="' . $filename . '"');
        } else if (preg_match('/Chrome\/([^\s]+)/i', $agent)) { 
            // $encoded_filename='chrome'.$encoded_filename;
        header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
        } else {
        $encoded_filename = str_replace("+", "%20", $encoded_filename);
        header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');        
        } 
        
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');

        exit;

    }
